package login

import (
	"context"
	"fmt"
	"service/conf"
	model "service/model/hr"
	"service/model/mod"

	gpb "gitee.com/cloudapex/protos/hr/pb"
	"gitee.com/cloudapex/ulern/htp"
	"github.com/gin-gonic/gin"
)

/*
 * 描述: 用户登陆
 * 路由: login/quickLogin
 * 方法: GET
 * 备注: 登陆服务独立,此接口作废
 *********************************************************************/
type UserLogin struct {
	Phone string `form:"phone" json:"phone" binding:"required"` //登录手机号
	Pass  string `form:"pass" json:"pass" binding:"required"`   //登录密码
}

func (this *UserLogin) Handle(c *gin.Context, ctx context.Context) htp.Response {
	rsp, err := model.StaffServer.UserLogin(ctx, &gpb.StaffBaseReq{
		Phone: this.Phone,
		Pass:  this.Pass,
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}

	rsps, err := model.StaffServer.GetStaffShows(ctx, &gpb.StaffShowsReq{Hids: []int64{rsp.HId}})
	if err != nil {
		return htp.RespModelErr("", err)
	}
	if len(rsps.StaffShows) == 0 {
		return htp.RespErr(1, "组织架构Id为空", nil)
	}
	shows := []uint64{}
	for _, it := range rsps.StaffShows {
		shows = append(shows, it.ShowUIntId)
	}

	token, err_ := htp.JWT([]byte(conf.Main.Listn().SvrSignKey)).CreateToken(&mod.CustomClaims{
		Name:   rsp.Name,
		Phone:  rsp.Phone,
		UId:    rsp.Id,
		CId:    rsp.CId,
		HId:    rsp.HId,
		WorkId: rsp.WorkId,
		ShowId: shows,
		RoleId: rsp.RoleId,
	})
	if err_ != nil {
		return htp.RespErr(htp.CodeTokenErr, token, err_)
	}
	return htp.RespOK("", &struct {
		Token string            `json:"token"`
		Staff *gpb.StaffBaseRes `json:"staff"`
	}{token, rsp})
}

/*
 * 描述: 手机号查询当前员工信息
 * 路由: staff/getStaff
 * 方法: GET
 *********************************************************************/
type QueryPhone struct {
	Phone string `form:"phone" json:"phone"` //手机号
	Name  string `form:"name" json:"name"`   //姓名
}

func (this *QueryPhone) Handle(c *gin.Context, ctx context.Context) htp.Response {
	rsp, err := model.StaffServer.HrGetUser(ctx, &gpb.HrBaseReq{
		Phone: this.Phone,
		Name:  this.Name,
		CId:   1,
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}
	if rsp.Status != 0 {
		return htp.RespErr(int(rsp.Status), rsp.Message, nil)
	}
	fmt.Println(rsp)
	var fage, quit bool
	//未登记  没离职的状态
	if rsp.ModelDetails.StaffInOut.State != 3 {
		if rsp.ModelDetails.BaseRes.State == 1 {
			fage = true
		}
		if rsp.ModelDetails.StaffInOut.State == 2 && rsp.ModelDetails.BaseRes.State == 2 {
			fage = false
		}
	} else {
		// if rsp.ModelDetails.StaffInOut.State == 3 && rsp.ModelDetails.BaseRes.State == 1 {

		// }
		quit = true
	}
	return htp.RespOK("", &struct {
		UserId   int64  `json:"userId"`
		Name     string `json:"userName"`
		CId      int64  `json:"cId"`
		WorkNmae string `json:"workNmae"`
		InAt     int64  `json:"inAt"`
		Status   bool   `json:"status"`
		Quit     bool   `json:"quit"`
		IdCard   string `json:"idCard"`
	}{rsp.ModelDetails.BaseRes.Id, rsp.ModelDetails.BaseRes.NumberName, rsp.ModelDetails.BaseRes.CId, rsp.ModelDetails.BaseRes.WName, rsp.ModelDetails.StaffInOut.InAt, fage, quit, rsp.ModelDetails.BaseRes.NumberId})
}

/*
 * 描述: 花名册信息入库
 * 路由: staff/queryStaffInfo
 * 方法: POST
 *********************************************************************/

type StaffHrDetail struct {
	UserId      int64  `form:"userId" json:"userId" binding:"required"`                   //员工ID
	CId         int64  `form:"cId" json:"cId" binding:"required"`                         //公司ID
	City        string `form:"city" json:"city"`                                          //城市
	TjUserId    int64  `form:"tjUserId" json:"tjUserId"`                                  //推荐ID
	NumberId    string `form:"cardId" json:"cardId" binding:"required,max=18"`            //身份证号
	NumberName  string `form:"cardName" json:"cardName" binding:"required"`               //身份证姓名
	Sex         int32  `form:"sex" json:"sex" binding:"required"`                         //性别: 1 默认，2 男，3 女
	Name        string `form:"userName" json:"userName" binding:"required"`               //姓名
	Birthday    int64  `form:"birthDay" json:"birthDay" binding:"required"`               //出生日期
	Phone       string `form:"phone" json:"phone" binding:"required"`                     //手机号
	HujiType    int32  `form:"hujiType" json:"hujiType" binding:"required"`               //户籍类型：1 默认，2 农业户籍，3 非农业户籍
	HujiAddress string `form:"hujiAddress" json:"hujiAddress" binding:"required,max=200"` //户籍地址
	NowAddress  string `form:"nowAddress" json:"nowAddress" binding:"required,max=200"`   //当前住址
	Emall       string `form:"email" json:"email"`                                        //电子邮件
	Marriage    int32  `form:"marriAge" json:"marriAge" binding:"required"`               //婚姻状态：1默认， 1 未婚，2 已婚
	NumberUrl   string `form:"cardUrl" json:"cardUrl" binding:"required"`                 //身份证照片（ http://yuxue.net/number_before.jpg,http://yuxue.net/number_after.jpg ）前/后
	UrgentName  string `form:"urgentName" json:"urgentName" binding:"required"`           //紧急联系人姓名
	UrgentPhone string `form:"urgentPhone" json:"urgentPhone" binding:"required"`         //紧急联系人手机号
	/*CardNumber  string `form:"cardNumber" json:"cardNumber" binding:"required"`           //银行卡号
	BankInfo    string `form:"bankInfo" json:"bankInfo" binding:"required"`               //支行信息
	BankType    int64  `form:"bankType" json:"bankType" binding:"required"`               //银行卡类型
	BankUrl     string `form:"bankUrl" json:"bankUrl" binding:"required"`                 //银行卡照片*/
	EduImage  string `form:"eduImage" json:"eduImage"` //毕业证照片
	TWorkId   int64  `form:"tWorkId" json:"tWorkId"`   //招聘人工号
	EduCation []struct {
		EduCation  int64  `form:"eduCation" json:"eduCation"`   //学历
		SchoolName string `form:"schoolName" json:"schoolName"` //学校
		InAt       int64  `form:"inAt" json:"inAt"`             //入学时间
		OutAt      int64  `form:"outAt" json:"outAt"`           //毕业时间
		MaJor      string `form:"maJor" json:"maJor"`           //专业
	} `json:"eduCation"`
	BankInfo []struct {
		Id         int64  `form:"bankId" json:"bankId"`         //银行卡ID
		CardNumber string `form:"cardNumber" json:"cardNumber"` //银行卡号
		BankInfo   string `form:"bankInfo" json:"bankInfo"`     //支行信息
		BankType   int64  `form:"bankType" json:"bankType"`     //银行卡类型
		BankUrl    string `form:"bankUrl" json:"bankUrl"`       //银行卡照片
	} `json:"bankInfos"`
}

func (this *StaffHrDetail) Handle(c *gin.Context, ctx context.Context) htp.Response {
	rsp, err := model.StaffServer.UpdateUser(ctx, &gpb.HrBaseReq{
		Id:          this.UserId,
		CId:         1,
		NumberId:    this.NumberId,
		City:        this.City,
		NumberName:  this.NumberName,
		Sex:         this.Sex,
		Name:        this.Name,
		Birthday:    this.Birthday,
		Phone:       this.Phone,
		HujiType:    this.HujiType,
		HujiAddress: this.HujiAddress,
		NowAddress:  this.NowAddress,
		Emall:       this.Emall,
		Marriage:    this.Marriage,
		NumberUrl:   this.NumberUrl,
		UrgentName:  this.UrgentName,
		UrgentPhone: this.UrgentPhone,
		EducImg:     this.EduImage,
		TuijianUid:  this.TjUserId,
		TWorkId:     this.TWorkId,
	})
	fmt.Println(err)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	if rsp.Status != 0 {
		return htp.RespErr(int(rsp.Status), "更新员工基本信息失败", nil)
	}
	//添加教育经历
	if len(this.EduCation) > 0 {
		for _, v := range this.EduCation {
			_, err = model.StaffServer.AddEdu(ctx, &gpb.StaffEdu{
				Hid:        this.UserId,
				Education:  v.EduCation,
				SchoolName: v.SchoolName,
				InAt:       v.InAt,
				OutAt:      v.OutAt,
				Major:      v.MaJor,
			})
			if err != nil {
				return htp.RespErr(int(rsp.Status), "更新员工基本信息失败", nil)
			}
		}
	}
	//添加银行卡信息
	if len(this.BankInfo) > 0 {
		var banks []*gpb.StaffBank
		for _, v := range this.BankInfo {
			bank := new(gpb.StaffBank)
			bank.Hid = this.UserId
			bank.CardNumber = v.CardNumber
			bank.BankUrl = v.BankUrl
			bank.BankType = v.BankType
			bank.BankInfo = v.BankInfo
			banks = append(banks, bank)
		}
		var req = new(gpb.StaffBankReq)
		req.StaffBanks = banks
		rsp, err := model.StaffServer.AddBank(ctx, req)
		fmt.Println(err)
		if err != nil {
			return htp.RespModelErr("", err)
		}
		if rsp.Status != 0 {
			return htp.RespModelErr("更新员工基本信息失败", nil)
		}
	}

	/*b := &model.StaffBackInfo{
		gpb.StaffBank{
			Hid:        this.UserId,
			CardNumber: this.CardNumber,
			BankInfo:   this.BankInfo,
			BankType:   this.BankType,
			BankUrl:    this.BankUrl,
		},
	}
	_, err = b.AddStaffBackInfo(ctx)*/
	fmt.Println(err)
	if err != nil {
		return htp.RespModelErr("更新员工基本信息失败", nil)
	}
	_, err = model.StaffServer.SetStaffMod(ctx, &gpb.StffModReq{
		UserId: this.UserId,
		Status: 2,
	})
	fmt.Println(err)
	if err != nil {
		return htp.RespModelErr("更新员工基本信息失败", nil)
	}
	return htp.RespOK("", nil)
}

/*
 * 描述: 模糊匹配员工身份信息
 * 路由: login/queryStaffList
 * 方法: GET
 *********************************************************************/
type QueryStaffList struct {
	Name string `form:"staffName" json:"staffName"`        //员工名称
	CId  int64  `form:"cId" json:"cId" binding:"required"` //公司ID
}

func (this *QueryStaffList) Handle(c *gin.Context, ctx context.Context) htp.Response {
	rsp, err := model.StaffServer.SearchUserList(ctx, &gpb.BaseSearchReq{
		CId:  this.CId,
		Name: this.Name,
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}
	return htp.RespOK("", rsp)
}

/*
 * 描述: 模糊匹配员工身份信息
 * 路由: login/queryStaffNoConnList
 * 方法: GET
 *********************************************************************/
type QueryStaffNoConnList struct {
	Name string `form:"staffName" json:"staffName"`        //员工名称
	CId  int64  `form:"cId" json:"cId" binding:"required"` //公司ID
}
type HrInfoRes struct {
	Id     int64  `json:"id"`     // 用户id
	Name   string `json:"name"`   // 名称
	WorkId int64  `json:"workId"` // 工号
	Phone  string `json:"phone"`  // 手机号
}

func (this *QueryStaffNoConnList) Handle(c *gin.Context, ctx context.Context) htp.Response {

	rsp, err := model.CrmUser.UserNoRelationList(ctx, &gpb.HrInfoListReq{
		CId:  this.CId,
		Name: this.Name,
	})
	if err != nil {
		return htp.RespModelErr("", err)
	}

	hrList := make([]HrInfoRes, 0)
	for _, value := range rsp.Data {
		hrList = append(hrList, HrInfoRes{
			Id:     value.Id,
			Name:   value.NumberName,
			WorkId: value.WorkId,
			Phone:  value.Phone,
		})
	}

	return htp.RespOK("", hrList)
}
